'use strict';
const dbHelper = require("db-helper")
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
const WxPubApi = require("wx-public-api")
const wxPubApi = new WxPubApi()
const moment = require('moment-timezone')
const oneMonth = 30 * 24 * 60 * 60 * 1000
const halfMonth = 15 * 24 * 60 * 60 * 1000
const oneWeek = 7 * 24 * 60 * 60 * 1000

async function downgrade(member) {
	if (member.wx_unionid) {
		let wxPubUser = await db.collection('t3ds-wx-pub-user')
			.where({
				unionId: member.wx_unionid,
				city: member.city
			})
			.field({
				openId: true
			})
			.get()
		console.log("wxPubUser: ", wxPubUser);
		if (wxPubUser.data[0]) {
			let temp = await dbHelper.getOne('t3ds-region', {
				'city.value': member.city
			})
			let tempId = temp.templateMsgs.find(item => {
				return item.templateName === '达人等级降级警告通知'
			}).templateID
			console.log("tempId: ", tempId);
			if (tempId) {
				try {
					await wxPubApi.sendTemplateMsg(member.city, {
						touser: wxPubUser.data[0].openId,
						template_id: tempId,
						data: {
							first: {
								value: '您已降级为普通用户'
							},
							keyword1: {
								value: '您已降级为普通用户'
							},
							keyword2: {
								value: moment().tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss")
							},
							remark: {
								value: '由于您最近1个月内没有通过分享和购买商品而获得收益，根据达人规则，您已被降级为普通用户，团队清零！如有疑问，请联系客服！'
							}
						}
					})
				} catch (e) {
					console.error('发送通知失败：' + e)
				}
			} else {
				console.log(`模板不存在，无法发送通知`)
			}
		} else {
			console.log(`用户没有关注 ${member.city} 公众号，无法发送通知`)
		}
	} else {
		console.log("用户没有wx_unionid，无法发送通知")
	}
}

async function sendRemind(member) {
	if (member.wx_unionid) {
		let wxPubUser = await db.collection('t3ds-wx-pub-user')
			.where({
				unionId: member.wx_unionid,
				city: member.city
			})
			.field({
				openId: true
			})
			.get()
		console.log("wxPubUser: ", wxPubUser);
		if (wxPubUser.data[0]) {
			let temp = await dbHelper.getOne('t3ds-region', {
				'city.value': member.city
			})
			let tempId = temp.templateMsgs.find(item => {
				return item.templateName === '达人等级降级警告通知'
			}).templateID
			console.log("tempId: ", tempId);
			if (tempId) {
				try {
					await wxPubApi.sendTemplateMsg(member.city, {
						touser: wxPubUser.data[0].openId,
						template_id: tempId,
						data: {
							first: {
								value: '您已降级为普通用户'
							},
							keyword1: {
								value: '您已降级为普通用户'
							},
							keyword2: {
								value: moment().tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss")
							},
							remark: {
								value: '由于您最近1个月内没有通过分享和购买商品而获得收益，根据达人规则，您已被降级为普通用户，团队清零！如有疑问，请联系客服！'
							}
						}
					})
				} catch (e) {
					console.error('发送通知失败：' + e)
				}
			} else {
				console.log(`模板不存在，无法发送通知`)
			}
		} else {
			console.log(`用户没有关注 ${member.city} 公众号，无法发送通知`)
		}
	} else {
		console.log("用户没有wx_unionid，无法发送通知")
	}
}

exports.main = async (event, context) => {

	try {
		//需要发送降级提醒的达人，每隔1周提醒一次，上一次获得收益距今半个月后开始检查
		let remindMemberRes = await db.collection("uni-id-users")
			.where({
				shareGrade: dbCmd.gt(0).and(dmCmd.lt(4)),
				lastNoticeDate: dbCmd.lt(Date.now() - oneWeek),
				latestIncomeTime: dbCmd.lt(Date.now() - halfMonth )
			})
			.field({
				_id: true,
				id: true,
				wx_unionid: true,
				registerShareExpertTime: true,
				city: true,
				latestIncomeTime: true,
				lastNoticeDate: true
			})
			.limit(500)
			.get()
		if (!remindMemberRes.data.length) {
			console.log('没有需要发送降级提醒的达人')
		}

		console.log('需要发送降级提醒的达人', remindMemberRes.data)
		// remindMemberRes.data.forEach(item => {
		// 	sendRemind(item)
		// })
		for (var i = 0; i < remindMemberRes.data.length; i++) {
			let m = remindMemberRes.data[i]
			await db.collection("uni-id-users").doc(m._id).update({
				lastNoticeDate: Date.now()
			})
		}

		//最近一次获得收益距今超过一个月的会员，要降级
		let degradedMembersRes = await db.collection("uni-id-users")
			.where({
				shareGrade: dbCmd.gt(0),
				latestIncomeTime: dbCmd.lt(Date.now() - oneMonth)
			})
			.field({
				_id: true,
				id: true,
				wx_unionid: true,
				registerShareExpertTime: true,
				city: true,
				lastNoticeDate: true
			})
			.limit(500)
			.get()

		if (!degradedMembersRes.data.length) {
			console.log('没有被降级的达人')
			return
		}
		console.log('被降级的达人', degradedMembersRes.data)
		let degradedMemberIds = degradedMembersRes.data.map(item => {
			return item._id
		})
		let relationRes = await db.collection("t3ds-share-expert-relation").where({
				userId: dbCmd.in(degradedMemberIds)
			})
			.limit(500)
			.get()
		let relationIds = relationRes.data.map(item => {
			return item._id
		})
		let transaction = await db.startTransaction()
		try {
			for (var i = 0; i < degradedMemberIds.length; i++) {
				let id = degradedMemberIds[i]
				await transaction.collection("uni-id-users").doc(id)
					.update({
						shareGrade: 0,
						lastNoticeDate: -1
					})
			}
			for (var i = 0; i < relationRes.data.length; i++) {
				let relation = relationRes.data[i]
				await transaction.collection("t3ds-share-expert-relation").doc(relation._id).remove()
				//如果下级达人非常多的情况下会有性能风险
				var pageNo = 1
				var pageSize = 1000
				while (true) {
					let childRelationRes = await db.collection("t3ds-share-expert-relation")
						.where({
							parentId: relation._id
						})
						.skip((pageNo - 1) * pageSize)
						.limit(pageSize).get()
					if (!childRelationRes.data.length) {
						break
					}
					for (var j = 0; j < childRelationRes.data.length; j++) {
						let childRelation = childRelationRes.data[j]
						await transaction.collection("t3ds-share-expert-relation").doc(childRelation._id)
							.update({
								parentId: ''
							})
					}
					pageNo++
				}
			}
			// degradedMembers.forEach((item => {
			// 	downgrade(item)
			// }))
			await transaction.commit()
		} catch (e) {
			console.error(e)
			await transaction.rollback()
		}
	} catch (e) {
		console.error(e);
	}
};
